// src/utils/throttle.js

export function throttle(func, wait) {
  let timeout = null;
  let lastArgs = null;
  let lastThis = null;
  let lastCallTime = 0;

  const throttled = function (...args) {
    const now = new Date().getTime();
    const remainingTime = wait - (now - lastCallTime);
    lastArgs = args;
    lastThis = this;

    if (remainingTime <= 0) {
      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
      }
      lastCallTime = now;
      func.apply(lastThis, lastArgs);
    } else if (!timeout) {
      timeout = setTimeout(() => {
        lastCallTime = !timeout ? lastCallTime + wait : new Date().getTime();
        timeout = null;
        func.apply(lastThis, lastArgs);
      }, remainingTime);
    }
  };

  return throttled;
}
